import React, { useEffect } from 'react';
import PropTypes from 'prop-types';

// import useViewport from '../../../hooks/useViewport';
import { getLayers, updateLayerGroup } from '../Util';
import memo from '../../common/wrapMemo';

import style from './BaseMap.module.scss';

const {L} = window;

// L.CRS.CustomEPSG4326 = L.extend({}, L.CRS.Earth, {
//     code: 'EPSG:4326',
//     projection: L.Projection.LonLat,
//     transformation: new L.Transformation(1 / 180, 1, -1 / 180, 0.5),
//     scale: function (zoom) {
//         return 256 * Math.pow(2, zoom - 1);
//     },
// });

const {CENTER, ZOOM, MINZOOM, BOUNDS} = window.CONFIG;

const BaseMap = memo((props) => {
    const { map, onMapLoaded, mapInfo, layerGroup } = props;

    // useViewport(map, viewport);

    useEffect(() => {
        // const center = [viewport.getIn(['center', 0]), viewport.getIn(['center', 1])];
        // const zoom = viewport.get('zoom');
        if (!map) {
            const tdtMap = (window.map = L.map('map', {
                center:[CENTER[1], CENTER[0]],
                zoom: ZOOM,
                worldCopyJump: true,
                maxZoom: 18,
                minZoom: MINZOOM,
                layers: layerGroup,
                zoomControl: false,
                attributionControl: false,
                // crs: L.CRS.CustomEPSG4326,
                crs: L.CRS.EPSG3857,
                maxBounds: BOUNDS
            }));
            onMapLoaded(tdtMap);
        }
    }, [map, onMapLoaded]);

    useEffect(() => {
        if (map) {
            const { TOKEN: token } = window.CONFIG;
            const { type, projection, name, domains } = mapInfo.toJS();

            const layers = getLayers({ type, projection, name, domains, token });

            // 更新图层组
            updateLayerGroup(layerGroup, layers, 'base');
        }
    },[map, mapInfo, layerGroup])

    return (
        <>
            <div id="map" className={style.baseMap}></div>
        </>
    )
});

BaseMap.displayName = 'BaseMap';

BaseMap.propTypes = {
    show: PropTypes.bool,
    map: PropTypes.object,
    mapInfo: PropTypes.object,
    viewport: PropTypes.object,
    onMapLoaded: PropTypes.func,
    layerGroup: PropTypes.object,
};

export default BaseMap;
